package com.baidu.mpks.filter;


import com.baidu.mpks.user.domain.User;
import com.baidu.mpks.user.service.UserService;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Component
public class ShenFeiTokenFilter extends AccessControlFilter {
    private static final Logger log = LoggerFactory.getLogger(ShenFeiTokenFilter.class);
    private static UserService userService;
    private static String host;
    private static String redirectUrl;

    public ShenFeiTokenFilter(UserService userService) {
        ShenFeiTokenFilter.userService = userService;
    }

    public void setHost(String host) {
        ShenFeiTokenFilter.host = host;
    }

    public void setRedirectUrl(String redirectUrl) {
        ShenFeiTokenFilter.redirectUrl = redirectUrl;
    }

    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String account = ((HttpServletRequest)servletRequest).getHeader("iv-user");
        log.info("===iv-user===:{}", account);
        User user = userService.findByAccount(account);
        if (ObjectUtils.isEmpty(user)) {
            response.setStatus(401);
            response.setHeader("login_error_msg", URLEncoder.encode("统一认证无权限", "UTF-8"));
            log.info("===indexRedirect===:{}", redirectUrl);
            response.sendRedirect(redirectUrl);
        } else {
            userService.login(account, "AVIC!@#789", false);
            log.info("===indexRedirect===:{}", host + "/frontend-fe/static/index.html#/");
            response.sendRedirect(host + "/frontend-fe/static/index.html#/");
        }

        return false;
    }

    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}